package com.shixun.milktea.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.shixun.milktea.entity.Manager;
import com.shixun.milktea.enums.ResultStatusEnum;

import com.shixun.milktea.mapper.ManagerMapper;
import com.shixun.milktea.service.ManagerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zrs
 * @since 2022-06-07
 */
@Service("userDetailsService")
public class ManagerServiceImpl extends ServiceImpl<ManagerMapper, Manager> implements ManagerService,UserDetailsService {

    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    ManagerMapper managerMapper;




    @Override
    public List<Manager> selectList() throws Exception {
        QueryWrapper<Manager> qw=new QueryWrapper<>();
        //构造查询条件
        return managerMapper.selectList(qw);
    }


    @Override
    public int saveAdmin(Manager manager) throws Exception {
        String password = manager.getPassword();
        //加密存储密码
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        String encode = encoder.encode(password);//加密返回密文密码
        manager.setManagerPassword(encode);
        return managerMapper.insert(manager);
    }

    @Override
    public UserDetails loadUserByUsername(String managerNickname) throws UsernameNotFoundException {
        Manager userDetails=null;
        try {
            QueryWrapper<Manager> qw=new QueryWrapper<>();
            qw.eq("manager_nickname",managerNickname);
            userDetails = managerMapper.selectOne(qw);
        } catch (Exception e) {
            throw  new UsernameNotFoundException(ResultStatusEnum.ERROR.getMsg());
        }
        if(userDetails==null){
            throw  new UsernameNotFoundException(ResultStatusEnum.USER_NOT_EXIST.getMsg());
        }
        return userDetails;
    }
}
